package com.bdqn.vueboot.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.vueboot.config.BascText;
import com.bdqn.vueboot.config.CustomException;
import com.bdqn.vueboot.config.R;
import com.bdqn.vueboot.dto.UserDto;
import com.bdqn.vueboot.entity.Certificate;
import com.bdqn.vueboot.entity.Department;
import com.bdqn.vueboot.entity.Static;
import com.bdqn.vueboot.entity.SysUser;
import com.bdqn.vueboot.mapper.CertificateMapper;
import com.bdqn.vueboot.mapper.DepartmentMapper;
import com.bdqn.vueboot.mapper.StaticMapper;
import com.bdqn.vueboot.mapper.SysUserMapper;
import com.bdqn.vueboot.service.CertificateService;
import com.bdqn.vueboot.service.SysUserService;
import com.bdqn.vueboot.util.UuidUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.core.lang.UUID.fastUUID;

/**
 *
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {
    @Autowired
    private SysUserMapper userRepository;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private StaticMapper staticMapper;
    @Autowired
    private CertificateMapper certificateMapper;

    @Override
    public SysUser findByUserNameBiz(String usrName) {
        return userRepository.selectOneByUsrName(usrName);
    }

    @Override
    public IPage<SysUser> findPageByMap(String usrName, IPage<SysUser> page) {
        // page.setRecords(userRepository.selectAllByUsrNameLikeOrderByUsrIdDesc(usrName,page));
//        QueryWrapper<SysUser> lambdaQueryWrapper=new QueryWrapper<>();
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(SysUser::getUsrName,usrName)
                .orderByAsc(SysUser::getUsrId);
        return userRepository.selectPage( page,lambdaQueryWrapper);
    }

//    @Override
//    public void saveUser(SysUser user) throws Exception {
//        userRepository.addAll(user);
//    }
    @Override
    public void deleteByUserId(Long id) throws Exception {
//        userRepository.deleteById(id);
        SysUser user =new SysUser();
        user.setUsrId(id);
        user.setStaticId(25L);
        userRepository.updateById(user);

    }

    @Override
    public SysUser findByUserIdBiz(Long usrId) throws Exception {
        SysUser user = null;
//        if (userRepository.selectByUsrId(usrId).isPresent()) {
//            user = userRepository.findById(id).get();
//        }
        user=userRepository.selectById(usrId);
        return user;
    }
    @Override
    public SysUser findOneByUsrNameBiz(String usrName) {

        return userRepository.findOneByUsrName(usrName);
    }


    @Override
    public List<SysUser> allSysUserBiz() {
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        return userRepository.selectList(userQueryWrapper);
    }

    @Override
    public IPage list(IPage<SysUser> page, UserDto user) {


        LambdaQueryWrapper<SysUser>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(user.getUsrName()!=null&&user.getUsrName()!="",SysUser::getUsrName,user.getUsrName());
        queryWrapper.eq(user.getDepId()!=null&&user.getDepId()!=0,SysUser::getDepId,user.getDepId());
        queryWrapper.eq(user.getPost()!= null&&user.getPost()!="",SysUser::getPost,user.getPost());
        queryWrapper.ge(user.getCreationTime()!=null,SysUser::getCreationTime,user.getCreationTime());
        queryWrapper.le(user.getCreationTime1()!=null,SysUser::getCreationTime,user.getCreationTime1());
        IPage<SysUser> sysUserIPage = userRepository.selectPage(page, queryWrapper);
        List<UserDto> userDto = new ArrayList<>();
        IPage<UserDto> userDtoIPage=new Page<>();
        BeanUtils.copyProperties(sysUserIPage,userDtoIPage);
        for (SysUser users : sysUserIPage.getRecords()
             ) {
            UserDto userDtos= new UserDto();
            BeanUtils.copyProperties(users,userDtos);
            userDto.add(userDtos);
        }
        userDto= userDto.stream().map((item)->{
            SysUser sysUser = userRepository.selectById(item.getUsrnameId());
            if(sysUser!=null&&sysUser.getUsrName()!=null) {
                item.setUsrnameName(sysUser.getUsrName());
            }
            Static aStatic = staticMapper.selectById(item.getStaticId());
            if(aStatic!=null&&aStatic.getStaticName()!=null) {
                item.setStaticName(aStatic.getStaticName());
            }
            Department department = departmentMapper.selectById(item.getDepId());
            if(department!=null&&department.getDepartmentName()!=null) {
                item.setDepName(department.getDepartmentName());
            }

                LambdaQueryWrapper<Certificate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.in(Certificate::getUsrId, item.getUsrId());
            Certificate certificate = certificateMapper.selectOne(lambdaQueryWrapper);
            if (certificate != null ) {
                item.setSite(certificate.getSite());
                item.setSiteName(certificate.getSiteName());
                item.setSitesuffix(certificate.getSiteSuffix());
                item.setSiteOriginal(certificate.getSiteOriginal());
                item.setSiteNum(certificate.getSite()+certificate.getSiteName()+certificate.getSiteSuffix());
                }

            return item;
        }).collect(Collectors.toList());

        userDtoIPage.setRecords(userDto);

        return userDtoIPage;
    }

    @Override
    @Transactional
    public int add(SysUser sysUser, MultipartFile file) {

        //拿到具体文件 file
        log.info("文件上传开始");
        log.info("文件{}",file.getOriginalFilename());
        Map<String,String> map = new HashMap<String,String>();
        if (!file.isEmpty()){
            try {
                String name = java.util.UUID.randomUUID().toString();
                String originalFilename = file.getOriginalFilename();
                String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
                //上传的文件需要保存的路径和文件名称，路径需要存在，否则报错
                String uri="D:\\images\\";
                file.transferTo(new File(uri+name+substring));
                map.put("uri","http://localhost:8005/img/");//后缀
                map.put("name",name);//随机生成的文件名
                map.put("originalFilename",originalFilename);//原文件名
                map.put("substring",substring);//后缀


            } catch (IllegalStateException | IOException e){
                e.printStackTrace();
                throw  new CustomException("上传失败");
            }
        } else {
            throw  new CustomException("请上传文件");
        }

        sysUser.setStaticId(23L);

        sysUser.setUsrnameId(BascText.getCarId());
        sysUser.setUsrPassword("123456");
        //UUID uuid = fastUUID();
//        UUID.randomUUID()0
        long l1 = UuidUtil.uniqId();
        sysUser.setUsrId(l1);
        int insert = userRepository.insert(sysUser);
      String uri=  map.get("uri");//保存地址
        String name=  map.get("name");//随机生成的文件名
        String originalFilename=  map.get("originalFilename");//原文件名
        String substring=  map.get("substring");//后缀
        Certificate certificate = new Certificate();
        certificate.setUsrId(l1);

        certificate.setSite(uri);
        certificate.setSiteName(name);
        certificate.setSiteSuffix(substring);
        certificate.setSiteOriginal(originalFilename);
        int insert1 = certificateMapper.insert(certificate);
        return insert1;
    }


}




